const TagInfoModal = {
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "详情",
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
    isEditMode: {
      type: Boolean,
      default: false,
    },
    isBatchMode: {
      type: Boolean,
      default: false,
    },
    selectedFiles: {
      type: Array,
      default: () => [],
    },
  },

  emits: ["close", "save"],

  data() {
    return {
      selectOptions: {
        productPhase: {},
        dataTypeFirst: {},
        dataTypeSecond: {},
        dataSource: {},
        channelNo: {},
        projectNo: {},
      },
      originalFormData: null, // 保存原始数据用于比较
    };
  },

  computed: {
    // 获取当前时间的 ISO 格式字符串（用于 datetime-local 的 max 属性）
    maxDateTime() {
      const now = new Date();
      // 将时间调整为本地时区，格式化为 YYYY-MM-DDTHH:mm
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day}T${hours}:${minutes}`;
    }
  },

  watch: {
    // 监听 formData 变化，保存原始数据
    formData: {
      handler(newData) {
        if (newData && Object.keys(newData).length > 0) {
          // 深拷贝保存原始数据
          this.originalFormData = JSON.parse(JSON.stringify(newData));
        }
      },
      immediate: true,
      deep: true,
    },
  },

  methods: {
    closeModal() {
      this.$emit("close");
    },

    // 验证必填字段
    validateRequiredFields() {
      const requiredFields = [
        { field: "projectNo", name: "项目编号" },
        { field: "deviceNo", name: "台架编号" },
        { field: "company", name: "单位" },
        { field: "dataTypeFirst", name: "数据第一分类" },
        { field: "dataTypeSecond", name: "数据第二分类" },
        { field: "productPhase", name: "产品阶段" },
        { field: "dataSource", name: "数据来源" },
        { field: "startTime", name: "运行起始时间" },
        { field: "engineNo", name: "发动机编号" },
      ];

      const missingFields = [];

      for (const { field, name } of requiredFields) {
        const value = this.formData[field];
        if (!value || (typeof value === "string" && value.trim() === "")) {
          missingFields.push(name);
        }
      }

      return missingFields;
    },

    // 验证地点输入
    validatePlaceInput() {
      const place = this.formData.place;

      // 如果地点为空，直接通过验证
      if (!place || place.trim() === "") {
        return { isValid: true };
      }

      const trimmedPlace = place.trim();

      // 检查长度限制（最大50个字符）
      if (trimmedPlace.length > 50) {
        return {
          isValid: false,
          message: "地点长度不能超过50个字符",
        };
      }

      // 检查是否包含特殊字符（只允许中文、英文、数字、空格、连字符、下划线、括号）
      const validPattern = /^[\u4e00-\u9fa5a-zA-Z0-9\s\-_()（）]+$/;
      if (!validPattern.test(trimmedPlace)) {
        return {
          isValid: false,
          message: "地点只能包含中文、英文、数字、空格、连字符、下划线和括号",
        };
      }

      // 检查是否包含连续的空格
      if (/\s{2,}/.test(trimmedPlace)) {
        return {
          isValid: false,
          message: "地点不能包含连续的空格",
        };
      }

      // 检查是否只包含空格或特殊字符
      if (/^[\s\-_()（）]+$/.test(trimmedPlace)) {
        return {
          isValid: false,
          message: "地点不能只包含空格或特殊字符",
        };
      }

      return { isValid: true };
    },

    // 检测数据是否发生变化
    hasDataChanged() {
      if (!this.originalFormData) {
        return true; // 如果没有原始数据，认为有变化
      }

      // 比较当前数据和原始数据
      return (
        JSON.stringify(this.formData) !== JSON.stringify(this.originalFormData)
      );
    },

    saveTagInfo() {
      // 检查数据是否发生变化
      if (!this.hasDataChanged()) {
        ElMessage.info("数据未发生变化，无需保存");
        return;
      }

      // 验证地点输入
      const placeValidation = this.validatePlaceInput();
      if (!placeValidation.isValid) {
        ElMessage.warning(placeValidation.message);
        return;
      }

      // 验证时间字段
      if (this.formData.startTime) {
        const startTime = new Date(this.formData.startTime);
        if (startTime > new Date()) {
          ElMessage.warning("运行起始时间不能超过当前时间");
          return;
        }
      }
      
      if (this.formData.uploadTime) {
        const uploadTime = new Date(this.formData.uploadTime);
        if (uploadTime > new Date()) {
          ElMessage.warning("上传时间不能超过当前时间");
          return;
        }
      }

      // 注意：批量修改和修改标签不需要校验必填字段，只有导入才需要校验
      // 这里移除了必填字段校验逻辑

      // 转换时间格式为后端期望的格式
      const formattedData = { ...this.formData };
      if (formattedData.startTime) {
        // 将 YYYY-MM-DDTHH:mm 格式转换为 yyyy-MM-dd HH:mm:ss 格式
        formattedData.startTime = this.formatDateTimeForBackend(
          formattedData.startTime
        );
      }
      if (formattedData.uploadTime) {
        // 将 YYYY-MM-DDTHH:mm 格式转换为 yyyy-MM-dd HH:mm:ss 格式
        formattedData.uploadTime = this.formatDateTimeForBackend(
          formattedData.uploadTime
        );
      }

      this.$emit("save", formattedData);
    },

    // 格式化时间为后端期望的格式
    formatDateTimeForBackend(dateTimeString) {
      if (!dateTimeString) return "";
      try {
        // 如果已经是 yyyy-MM-dd HH:mm:ss 格式，直接返回
        if (
          typeof dateTimeString === "string" &&
          /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(dateTimeString)
        ) {
          return dateTimeString;
        }

        // 处理 YYYY-MM-DDTHH:mm 格式（缺少秒）
        if (
          typeof dateTimeString === "string" &&
          /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(dateTimeString)
        ) {
          // 补充秒为00
          dateTimeString = dateTimeString + ":00";
        }

        // 将各种格式转换为 yyyy-MM-dd HH:mm:ss 格式
        const date = new Date(dateTimeString);
        if (isNaN(date.getTime())) {
          console.error("无效的时间格式:", dateTimeString);
          return "";
        }
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (error) {
        console.error("时间格式化失败:", error, "原始值:", dateTimeString);
        return "";
      }
    },

    // 处理地点输入
    onPlaceInput() {
      // 自动去除首尾空格
      if (this.formData.place) {
        this.formData.place = this.formData.place.trim();
      }
    },

    // 验证时间是否超过当前时间
    validateTime(fieldName) {
      const timeValue = this.formData[fieldName];
      if (!timeValue) return;
      
      const selectedTime = new Date(timeValue);
      const now = new Date();
      
      if (selectedTime > now) {
        const fieldLabel = fieldName === 'startTime' ? '运行起始时间' : '上传时间';
        ElMessage.warning(`${fieldLabel}不能超过当前时间`);
        // 将时间重置为当前时间
        this.formData[fieldName] = this.maxDateTime;
      }
    },

    // 获取选择器选项
    async loadSelectOptions() {
      try {
        const response = await axios.get(
          "/into-iotdb/file-record/select-options"
        );
        if (response.data.success) {
          this.selectOptions = response.data.data;
        } else {
          console.error("获取选择器选项失败:", response.data.message);
        }
      } catch (error) {
        console.error("获取选择器选项异常:", error);
      }
    },
  },

  mounted() {
    this.loadSelectOptions();
  },

  watch: {
    isEditMode(newVal) {},
  },

  template: `
        <div v-if="show" class="modal" @click="closeModal">
            <div class="modal-content" @click.stop>
                <div class="modal-header">
                    <h2 class="modal-title">{{ title }}</h2>
                    <span class="close" @click="closeModal">&times;</span>
                </div>
                
                <!-- 导入前必填标志说明 -->
                <div class="import-legend">
                    <div class="legend-text">
                        <span class="required">*</span>：在导入到IoTDB前必须填写完整
                    </div>
                </div>
                <!-- 批量修改提示 -->
                <div v-if="isBatchMode" class="batch-notice" >
                    <div class="notice-icon">i</div>
                    <div class="notice-content">
                    <strong>批量修改模式：</strong>
                        <p>您正在对{{selectedFiles.length}}条记录进行批量修改。填写以下信息将应用到所有选中的记录</p>
                        <div class="selected-files">
                            <strong>选中的文件：</strong>
                            <ul>
                                <li v-for="file in selectedFiles.slice(0, 3)" :key="file.id">{{ file.fileName }}</li>
                                <li v-if="selectedFiles.length > 3">...还有{{selectedFiles.length - 3}}条记录</li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <div class="modal-body">
                    <form @submit.prevent="saveTagInfo">
                        <!-- 基础信息 -->
                        <div class="form-section">
                            <div class="section-title">基础信息</div>
                            <div class="form-grid">
                                <div class="form-group">
                                    <label class="form-label">飞机编号</label>
                                    <input type="text" class="form-input" v-model="formData.planeNo" placeholder="请输入飞机编号" :readonly="!isEditMode">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">项目编号 <span class="required">*</span></label>
                                    <select class="form-select" v-model="formData.projectNo" :disabled="!isEditMode">
                                        <option value="">请选择项目编号</option>
                                        <option v-for="(label, value) in selectOptions.projectNo" :key="value" :value="value">{{ label }}</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">地点</label>
                                    <input 
                                        type="text" 
                                        class="form-input" 
                                        :class="{ 'input-error': !validatePlaceInput().isValid && formData.place }"
                                        v-model="formData.place" 
                                        placeholder="请输入地点（最多50个字符）" 
                                        :readonly="!isEditMode"
                                        maxlength="50"
                                        @input="onPlaceInput"
                                    >
                                    <div v-if="!validatePlaceInput().isValid && formData.place" class="error-message">
                                        {{ validatePlaceInput().message }}
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">单位 <span class="required">*</span></label>
                                    <input type="text" class="form-input" v-model="formData.company" placeholder="请输入单位" :readonly="!isEditMode">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">产品阶段 <span class="required">*</span></label>
                                    <select class="form-select" v-model="formData.productPhase" :disabled="!isEditMode">
                                        <option value="">请选择产品阶段</option>
                                        <option v-for="(label, value) in selectOptions.productPhase" :key="value" :value="value">{{ label }}</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">数据第一分类 <span class="required">*</span></label>
                                    <select class="form-select" v-model="formData.dataTypeFirst" :disabled="!isEditMode">
                                        <option value="">请选择第一分类</option>
                                        <option v-for="(label, value) in selectOptions.dataTypeFirst" :key="value" :value="value">{{ label }}</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">数据第二分类 <span class="required">*</span></label>
                                    <select class="form-select" v-model="formData.dataTypeSecond" :disabled="!isEditMode">
                                        <option value="">请选择第二分类</option>
                                        <option v-for="(label, value) in selectOptions.dataTypeSecond" :key="value" :value="value">{{ label }}</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">数据来源 <span class="required">*</span></label>
                                    <select class="form-select" v-model="formData.dataSource" :disabled="!isEditMode">
                                        <option value="">请选择数据来源</option>
                                        <option v-for="(label, value) in selectOptions.dataSource" :key="value" :value="label">{{ label }}</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">运行起始时间 <span class="required">*</span></label>
                                    <input 
                                        type="datetime-local" 
                                        class="form-input" 
                                        v-model="formData.startTime" 
                                        :readonly="!isEditMode"
                                        :max="maxDateTime"
                                        @change="validateTime('startTime')"
                                    >
                                </div>
                                <div class="form-group">
                                    <label class="form-label">通道编号</label>
                                    <select class="form-select" v-model="formData.channelNo" :disabled="!isEditMode">
                                        <option value="">请选择通道</option>
                                        <option v-for="(label, value) in selectOptions.channelNo" :key="value" :value="label">{{ label }}</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">台架编号 <span class="required">*</span></label>
                                    <input type="text" class="form-input" v-model="formData.deviceNo" placeholder="请输入台架编号" :readonly="!isEditMode">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">试验科目</label>
                                    <input type="text" class="form-input" v-model="formData.subject" placeholder="请输入科目" :readonly="!isEditMode">
                                </div>
                                <div class="form-group" style="grid-column: 1 / -1;">
                                    <label class="form-label">备注</label>
                                    <textarea class="form-textarea" v-model="formData.remark" placeholder="请输入备注信息" :readonly="!isEditMode"></textarea>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 发动机信息 -->
                        <div class="form-section">
                            <div class="section-title">发动机信息</div>
                            <div class="form-grid">
                                <div class="form-group">
                                    <label class="form-label">发动机ID</label>
                                    <input type="text" class="form-input" v-model="formData.engineId" placeholder="请输入发动机ID" :readonly="!isEditMode">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">发动机编号 <span class="required">*</span></label>
                                    <input type="text" class="form-input" v-model="formData.engineNo" placeholder="请输入发动机编号" :readonly="!isEditMode">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">发动机位置</label>
                                    <select class="form-select" v-model="formData.enginePlace" :disabled="!isEditMode">
                                        <option value="">请选择发动机位置</option>
                                        <option value="单发">单发</option>
                                        <option value="双发-左侧">双发-左侧</option>
                                        <option value="双发-右侧">双发-右侧</option>
                                        <option value="三发-左">三发-左</option>
                                        <option value="三发-中">三发-中</option>
                                        <option value="三发-右">三发-右</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 控制器信息 -->
                        <div class="form-section">
                            <div class="section-title">控制器信息</div>
                            <div class="form-grid">
                                <div class="form-group">
                                    <label class="form-label">控制器ID</label>
                                    <input type="text" class="form-input" v-model="formData.ecuId" placeholder="请输入控制器ID" :readonly="!isEditMode">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">控制器编号</label>
                                    <input type="text" class="form-input" v-model="formData.ecuNo" placeholder="请输入控制器编号" :readonly="!isEditMode">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">控制系统ID</label>
                                    <input type="text" class="form-input" v-model="formData.ecuSysId" placeholder="请输入控制系统ID" :readonly="!isEditMode">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">控制系统编号</label>
                                    <input type="text" class="form-input" v-model="formData.ecuSysNo" placeholder="请输入控制系统编号" :readonly="!isEditMode">
                                </div>
                            </div>
                        </div>
                        
                        <!-- 时间信息 -->
                        <div class="form-section">
                            <div class="section-title">时间信息</div>
                            <div class="form-grid">
                                <div class="form-group">
                                    <label class="form-label">上传时间</label>
                                    <input 
                                        type="datetime-local" 
                                        class="form-input" 
                                        v-model="formData.uploadTime" 
                                        :readonly="!isEditMode"
                                        :max="maxDateTime"
                                        @change="validateTime('uploadTime')"
                                    >
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" @click="closeModal">关闭</button>
                                                <button v-if="isEditMode" type="button" class="btn btn-primary" @click="saveTagInfo">
                                                    {{ isBatchMode ? '批量保存' : '保存' }}
                                                </button>
                                            </div>
            </div>
        </div>
    `,
};

// 注册组件
if (typeof module !== "undefined" && module.exports) {
  module.exports = TagInfoModal;
}
